package com.topcoder.srm484;

public class CubeColoring {
	public long theCount(String[] colors) {
		long count = 0;
		int N = colors[0].length();
		int[] b = convert(colors);
		
		for (int w0=0; w0<N; w0++) {
			if ((b[0]>>w0 & 1) == 0) continue;
			
			for (int w2=0; w2<N; w2++) {
				if ((b[2]>>w2 & 1) == 0) continue;
				
				for (int w5=0; w5<N; w5++) {
					if ((b[5]>>w5 & 1) == 0) continue;
					
					for (int w7=0; w7<N; w7++) {
						if ((b[7]>>w7 & 1) == 0) continue;
						int w1 = possible(b[1], w0, w2, w5);
						int w3 = possible(b[3], w0, w2, w7);
						int w4 = possible(b[4], w0, w5, w7);
						int w6 = possible(b[6], w2, w5, w7);
						count += w1*w3*w4*w6;
					}
				}
			}
		}
		
		return count;
	}
	
	private int[] convert(String[] colors) {
		int[] b = new int[8];
		for (int i=0; i<8; i++) {
			for (int j=0; j<colors[0].length(); j++) {
				if (colors[i].charAt(j) == 'Y') b[i] |= 1 << j;
			}
		}
		return b;
	}
	
	private int possible(int b, int c1, int c2, int c3) {
		return Integer.bitCount(b & ~(1<<c1 | 1<<c2 | 1<<c3));
	}
	
	public long theCount2(String[] colors)
	{
		long res=0;
		int n=colors[0].length();
		for(int c0 = 0; c0 < n; c0++)
		for(int c2 = 0; c2 < n; c2++)
		for(int c5 = 0; c5 < n; c5++)
		for(int c7 = 0; c7 < n; c7++)
		{
			if(colors[0].charAt(c0)=='N' || colors[2].charAt(c2)=='N' ||
			   colors[5].charAt(c5)=='N' || colors[7].charAt(c7)=='N')
				continue;
			int w1=0, w3=0, w4=0, w6=0;
			for(int c = 0; c < n; c++)
			{
				if(colors[1].charAt(c)=='Y' && c!=c0 && c!=c2 && c!=c5)
					w1++;
				if(colors[3].charAt(c)=='Y' && c!=c0 && c!=c2 && c!=c7)
					w3++;
				if(colors[4].charAt(c)=='Y' && c!=c0 && c!=c5 && c!=c7)
					w4++;
				if(colors[6].charAt(c)=='Y' && c!=c2 && c!=c5 && c!=c7)
					w6++;
			}
			res += w1*w3*w4*w6;
		}
		return res;
	}
}
